package com.minio.controller;


import com.minio.domain.AjaxResult;
import com.minio.util.MinioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.simpleframework.xml.core.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文件操作接口")
@Controller
public class FileController {

	@Autowired
    MinioUtil minioUtil;

	@ApiOperation("上传一个文件")
	@RequestMapping(value = "/uploadfile/{bucket}/{path}", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult fileupload(@RequestParam MultipartFile[] files, @PathVariable(value = "bucket")  String bucket,
                                @PathVariable(value = "path")  String path) throws Exception {
		if(files ==null || files.length == 0 ){
			return AjaxResult.error("不能上传空文件");
		}
		if(StringUtils.isEmpty(bucket)){
			bucket="anonymous";
		}
		minioUtil.createBucket(bucket);

		List<String> urls = new ArrayList<>();
		for (MultipartFile file : files) {
			String url ;
			if (path != null) {
				url = minioUtil.uploadFile(file.getInputStream(), bucket, path+"/"+file.getOriginalFilename());
			} else {
				url = minioUtil.uploadFile(file.getInputStream(), bucket, file.getOriginalFilename());
			}
			urls.add(url);
		}
		String uri = org.apache.commons.lang3.StringUtils.join(urls, "&&");
		return AjaxResult.success(uri);
	}

	@ApiOperation("列出所有的桶")
	@RequestMapping(value = "/listBuckets", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResult listBuckets() throws Exception {
		return AjaxResult.success(minioUtil.listBuckets());
	}

	@ApiOperation("递归列出一个桶中的所有文件和目录")
	@RequestMapping(value = "/listFiles", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResult listFiles(@RequestParam String bucket) throws Exception {
		return AjaxResult.success("200", minioUtil.listFiles(bucket));
	}

	@ApiOperation("下载一个文件")
	@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
	@ResponseBody
	public void downloadFile(@RequestParam String bucket, @RequestParam String url,
                             HttpServletResponse response) throws Exception {
		InputStream stream = minioUtil.download(bucket, url);
		ServletOutputStream output = response.getOutputStream();
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(url.substring(url.lastIndexOf("/") + 1), "UTF-8"));
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
		IOUtils.copy(stream, output);
	}


	@ApiOperation("删除一个文件")
	@RequestMapping(value = "/deleteFile", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResult deleteFile(@RequestParam String bucket, @RequestParam String url) throws Exception {
		minioUtil.deleteObject(bucket, url);
		return AjaxResult.success();
	}

	@ApiOperation("删除一个桶")
	@RequestMapping(value = "/deleteBucket", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResult deleteBucket(@RequestParam String bucket) throws Exception {
		minioUtil.deleteBucket(bucket);
		return AjaxResult.success();
	}

	@ApiOperation("上传一个文件")
	@RequestMapping(value = "/netuploadfile/{bucket}", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult netfileupload(@RequestParam String url, @PathVariable(value = "bucket")  String bucket) throws Exception {

		if(StringUtils.isEmpty(bucket)){
			bucket="anonymous";
		}
		minioUtil.createBucket(bucket);

		URL urlstream = new URL(url);
		HttpURLConnection httpcon = (HttpURLConnection) urlstream.openConnection();
		httpcon.addRequestProperty("User-Agent", "Mozilla/5.0");
//                httpcon.addRequestProperty("cookie","PPA_CI=c735a7dde05f848555876474d645308d");
		//获取文件名
		String fileName = minioUtil.getUrlName(url);
		String uri = minioUtil.uploadFile(httpcon.getInputStream(), bucket,  fileName);
		return AjaxResult.success(uri);
	}
}
